<?php
require_once("userView.php");
require_once(CORE_DIR.'userModel.php');

class getimageAction extends Action{

	function __construct(){
		$this->view = new userView();
	}

	public function run($get, $post, $viewtype) {
		parent::run($get,$post,VS_PLUGIN);
		
		$userId = $get["userId"];
		$update = $get["update"];
		
		$uModel = new userModel();
		$user = $uModel->getUserData($userId);

		$ninjaUserImage = false;
		if(file_exists(HOME."www/imagesuser/".$user->getId()."/fullimg"))
			$ninjaUserImage = imagecreatefrompng(HOME."www/imagesuser/".$user->getId()."/fullimg");
		
		if(!$ninjaUserImage || (isset($update) && $update != null && $update == 1))
		{
			$ninjaUserImage = imagecreatefrompng(HOME."www/imagesuser/".$user->getId()."/img");
			
			if (isset($user->fbuid) && $user->fbuid != "") {
				$imageInfo = getimagesize("http://graph.facebook.com/".$user->getFBUid()."/picture");
				
				switch ($imageInfo["mime"]) {
					case "image/png":
						$fbUserImage = imagecreatefrompng("http://graph.facebook.com/".$user->getFBUid()."/picture");
						break;
					case "image/jpeg":
					case "image/jpg":
						$fbUserImage = imagecreatefromjpeg("http://graph.facebook.com/".$user->getFBUid()."/picture");
						break;
					case "image/gif":
						$fbUserImage = imagecreatefromgif("http://graph.facebook.com/".$user->getFBUid()."/picture");
						break;
				}
			}
			else {
				$fbUserImage = imagecreatefrompng(HOME."www/imagesuser/default.png");
			}
			
			$dest = imagecreatetruecolor(50, 50);
			$bgc = imagecolorallocate($dest, 255, 255, 255);
	        imagefilledrectangle($dest, 0, 0, 50, 50, $bgc);
			
			imagecopy($dest, $fbUserImage, 0, 0, 0, 0, 50, 50);
			imagecopy($dest, $ninjaUserImage, 0, 0, 0, 0, 50, 50);
			imagepng($dest, HOME."www/imagesuser/".$user->getId()."/fullimg");

			imagedestroy($dest);
			imagedestroy($ninjaUserImage);
			imagedestroy($fbUserImage);
		}
		
		$file = HOME."www/imagesuser/".$user->getId()."/fullimg";
	
		if (file_exists($file)) {
		    header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename='.basename($file));
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
		    exit;
		}		
		
	}
}
?>